package com.winit.openapi.wh.outbound.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.oms.spi.intelligent.recommend.command.IntelligentWarehouseReportListCommand;
import com.winit.oms.spi.intelligent.recommend.vo.IntelligentWarehouseMerchandise;
import com.winit.oms.spi.intelligent.recommend.vo.IntelligentWarehouseReport;
import com.winit.oms.spi.outbound.IntelligentWarehouseReportService;
import com.winit.oms.spi.outbound.OutboundIntelligentWarehouseService;
import com.winit.oms.spi.outbound.command.order.IntelligentWarehouseCommand;
import com.winit.oms.spi.outbound.vo.OutboundOrderIntelligentWarehouseResult;
import com.winit.oms.spi.outbound.vo.OutboundOrderVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.openapi.wh.outbound.builder.OutboundOrderBuilder;
import com.winit.openapi.wh.outbound.validator.OutboundOrderfieldValidator;

/**
 * 海外仓出库单智能推荐仓库
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * hui.li2 	1.0  		2016年11月10日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/intelligent/warehouse")
public class OutboundOrderIntelligentWarehouseController extends BaseController {

    @Resource
    private OutboundIntelligentWarehouseService outboundIntelligentWarehouseService;
    @Resource
    private IntelligentWarehouseReportService   intelligentWarehouseReportService;

    /**
     * 智能推荐仓库
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getIntelligentWarehouseList")
    public String getIntelligentWarehouseList(@ModelAttribute RequestMsg requestMsg,
                                              @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        IntelligentWarehouseCommand command = new IntelligentWarehouseCommand();
        List<OutboundOrderVo> list = new ArrayList<OutboundOrderVo>();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            JSONArray array = json.getJSONArray("orderList");
            if (null != array && array.size() > 0) {
                if (((JSONObject) obj).getBoolean("isOldProduct")) {
                    for (Object item : array) {
                        JSONObject jsonObject = (JSONObject) item;
                        OutboundOrderVo vo = OutboundOrderBuilder.bulidOldOrderVo(jsonObject,
                            ((JSONObject) obj).getString("isEbayOrder"));
                        vo.setIsOldProduct(true);
                        list.add(vo);
                    }
                } else {
                    for (Object item : array) {
                        JSONObject jsonObject = (JSONObject) item;
                        OutboundOrderfieldValidator.validImportOutboundOrder(jsonObject);
                        OutboundOrderVo vo = OutboundOrderBuilder.build(jsonObject);
                        vo.setIsOldProduct(false);
                        list.add(vo);
                    }
                }
            }
            command.setList(list);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        // 调用接口创建入库单
        OutboundOrderIntelligentWarehouseResult oiwVo = outboundIntelligentWarehouseService.getIntelligentWarehouseList(command);
        if (null != oiwVo) {
            map.put("noIntelligentWarehouseList", oiwVo.getNoIntelligentWarehouseList());
            map.put("intelligentWarehouseList", oiwVo.getIntelligentWarehouseList());
            map.put("stockInsufficientList", oiwVo.getStockInsufficientList());
            map.put("isEbayOrder", ((JSONObject) obj).getString("isEbayOrder"));
            if (null != oiwVo.getResponse()) {
                map.put("errorMsgList", oiwVo.getResponse().getErrorResultList());
                map.put("isSuccess", oiwVo.getResponse().getIsSuccess());
                map.put("resultCount", oiwVo.getResponse().getResultCount());
            }
        }
        responseMsg.setData(map);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 保存智能推荐仓库
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/saveIntelligentWarehouseList")
    public String saveIntelligentWarehouseList(@ModelAttribute RequestMsg requestMsg,
                                               @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        IntelligentWarehouseReportListCommand command = new IntelligentWarehouseReportListCommand();
        List<IntelligentWarehouseReport> orderList = new ArrayList<IntelligentWarehouseReport>();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            JSONArray array = json.getJSONArray("orderList");
            if (null != array && array.size() > 0) {
                for (Object item : array) {
                    JSONObject jsonObject = (JSONObject) item;
                    IntelligentWarehouseReport vo = this.build(jsonObject);
                    orderList.add(vo);
                }
            }
            command.setOrderList(orderList);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        intelligentWarehouseReportService.createIntelligentWarehouseReportList(command);

        return SUCCESS;
    }

    /**
     * 构建共用参数
     * 
     * @param json
     */
    private IntelligentWarehouseReport build(JSONObject json) {
        IntelligentWarehouseReport vo = new IntelligentWarehouseReport();
        // 校验必填项
        ValidateUtil.validNotNull(json, "winitOrderNo");
        ValidateUtil.validNotNull(json, "type");
        ValidateUtil.validNotNull(json, "customerCode");
        ValidateUtil.validNotNull(json, "sourceWarehouseCode");
        ValidateUtil.validNotNull(json, "sourceWarehouseName");
        // ValidateUtil.validNotNull(json, "sourceProductCode");
        ValidateUtil.validNotNull(json, "sourceProductName");
        // ValidateUtil.validNotNull(json, "sourceSla");

        vo.setWinitOrderNo(json.getString("winitOrderNo"));
        vo.setType(json.getString("type"));
        vo.setOrderSource(json.getString("orderSource"));
        vo.setCustomerCode(json.getString("customerCode"));
        vo.setCustomerOrderNo(json.getString("customerOrderNo"));
        vo.setBuyerName(json.getString("buyerName"));
        vo.setBuyerPhone(json.getString("buyerPhone"));
        vo.setBuyerEmail(json.getString("buyerEmail"));
        vo.setBuyerHouseNo(json.getString("buyerHouseNo"));
        vo.setBuyerCountry(json.getString("buyerCountry"));
        vo.setBuyerState(json.getString("buyerState"));
        vo.setBuyerCity(json.getString("buyerCity"));
        vo.setBuyerPostcode(json.getString("buyerPostcode"));
        vo.setBuyerAddress1(json.getString("buyerAddress1"));
        vo.setEbayBuyerId(json.getString("ebayBuyerId"));
        vo.setEbaySellerId(json.getString("ebaySellerId"));
        vo.setSourceWarehouseCode(json.getString("sourceWarehouseCode"));
        vo.setSourceWarehouseName(json.getString("sourceWarehouseName"));
        vo.setSourceProductCode(json.getString("sourceProductCode"));
        vo.setSourceProductName(json.getString("sourceProductName"));
        vo.setSourceSla(json.getLong("sourceSla"));
        vo.setSourceFee(json.getBigDecimal("sourceFee"));
        vo.setRecommendWarehouseCode(json.getString("recommendWarehouseCode"));
        vo.setRecommendWarehouseName(json.getString("recommendWarehouseName"));
        vo.setRecommendProductCode(json.getString("recommendProductCode"));
        vo.setRecommendProductName(json.getString("recommendProductName"));
        vo.setRecommendSla(json.getLong("recommendSla"));
        vo.setRecommendFee(json.getBigDecimal("recommendFee"));
        vo.setNoWarehouseCode(json.getString("noWarehouseCode"));
        vo.setNoWarehouseName(json.getString("noWarehouseName"));
        vo.setNoProductCode(json.getString("noProductCode"));
        vo.setNoProductName(json.getString("noProductName"));
        vo.setNoSla(json.getLong("noSla"));
        vo.setNoFee(json.getBigDecimal("noFee"));
        vo.setErrorCode(json.getString("errorCode"));
        vo.setErrorMsg(json.getString("errorMsg"));

        JSONArray array = json.getJSONArray("merchandiseList");

        List<IntelligentWarehouseMerchandise> merchandiseList = new ArrayList<IntelligentWarehouseMerchandise>();
        for (Object item : array) {
            JSONObject obj = (JSONObject) item;
            IntelligentWarehouseMerchandise merchandise = new IntelligentWarehouseMerchandise();
            merchandise.setWinitOrderNo(json.getString("winitOrderNo"));
            merchandise.setCustomerOrderNo(vo.getCustomerOrderNo());
            merchandise.setDispatchQty(obj.getLong("estimateDispatchQty"));
            merchandise.setNameCn(obj.getString("nameCn"));
            merchandise.setNameEn(obj.getString("nameEn"));
            merchandise.setMerchandiseSerno(obj.getString("merchandiseSerno"));
            merchandise.setMerchandiseCode(obj.getString("merchandiseCode"));
            merchandise.setEbayItemId(obj.getString("ebayItemId"));
            merchandise.setEbayTransactionId(obj.getString("ebayTransactionId"));
            merchandise.setSpecification(obj.getString("specification"));
            merchandiseList.add(merchandise);
        }

        vo.setMerchandiseList(merchandiseList);

        return vo;
    }
}
